<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Book;
use Illuminate\Validation\ValidationException;

class BookController extends Controller
{
    /**
     * 获取所有书籍列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        try {
            $books = Book::orderBy('created_at', 'desc')->get();
            
            return response()->json([
                'success' => true,
                'message' => '获取书籍列表成功',
                'data' => $books
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取书籍列表失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 创建新书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'author' => 'required|string|max:255',
                'description' => 'required|string',
                'price' => 'required|numeric|min:0',
                'image' => 'nullable|string|max:500',
                'category' => 'required|string|max:100',
                'publisher' => 'required|string|max:255',
            ]);

            $book = Book::create($validated);

            return response()->json([
                'success' => true,
                'message' => '书籍创建成功',
                'data' => $book
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 显示指定书籍详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $book = Book::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'message' => '获取书籍详情成功',
                'data' => $book
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取书籍详情失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新指定书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $book = Book::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            $validated = $request->validate([
                'title' => 'sometimes|string|max:255',
                'author' => 'sometimes|string|max:255',
                'description' => 'sometimes|string',
                'price' => 'sometimes|numeric|min:0',
                'image' => 'nullable|string|max:500',
                'category' => 'sometimes|string|max:100',
                'publisher' => 'sometimes|string|max:255',
            ]);

            $book->update($validated);

            return response()->json([
                'success' => true,
                'message' => '书籍更新成功',
                'data' => $book
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除指定书籍
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $book = Book::find($id);
            
            if (!$book) {
                return response()->json([
                    'success' => false,
                    'message' => '书籍不存在'
                ], 404);
            }

            $book->delete();

            return response()->json([
                'success' => true,
                'message' => '书籍删除成功'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除书籍失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 搜索书籍
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request)
    {
        try {
            $query = $request->get('q');
            $category = $request->get('category');
            
            $books = Book::query();
            
            if ($query) {
                $books->where(function($q) use ($query) {
                    $q->where('title', 'like', "%{$query}%")
                      ->orWhere('author', 'like', "%{$query}%")
                      ->orWhere('description', 'like', "%{$query}%");
                });
            }
            
            if ($category) {
                $books->where('category', $category);
            }
            
            $books = $books->orderBy('created_at', 'desc')->get();

            return response()->json([
                'success' => true,
                'message' => '搜索完成',
                'data' => $books
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '搜索失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}